package com.mango.community.controller;

import com.mango.community.entity.Comment;
import com.mango.community.entity.DiscussPost;
import com.mango.community.entity.Event;
import com.mango.community.event.EventProducer;
import com.mango.community.service.CommentService;
import com.mango.community.service.DiscussPostService;
import com.mango.community.util.CommunityConstant;
import com.mango.community.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Date;

/**
 * @Author:  MangoCookieMilk
 * @Date:     2020/7/26 22:49
 */
@Controller
@RequestMapping("/comment")
public class CommentController implements CommunityConstant {
    @Autowired
    private CommentService commentService;
    @Autowired
    private HostHolder hostHolder;
    /**
     * 注入生产者
     */
    @Autowired
    private EventProducer eventProducer;
    @Autowired
    private DiscussPostService discussPostService;

    /** 添加评论
     * @param id 帖子的id
     * @param comment 评论的实体类
     * @return
     */
    @PostMapping("/add/{id}")
    public String addComment(@PathVariable("id") int id, Comment comment){
        //设置评论的用户
        comment.setUserId(hostHolder.getUser().getId());
        //设置评论的状态
        comment.setStatus(0);
        //设置评论的创建时间
        comment.setCreateTime(new Date());
        //添加评论
        commentService.addComment(comment);
        //设置event对象的值，消费者所需要的事件的数据
        Event event = new Event()
                .setTopic(TOPIC_COMMENT)
                .setUserId(hostHolder.getUser().getId())
                .setEntityType(comment.getEntityType())
                .setEntityId(comment.getEntityId())
                .setData("postId",id);
        if (comment.getEntityType() == ENTITY_TYPE_POST){
            //评论 帖子时
            DiscussPost target = discussPostService.findDiscussPostById(comment.getEntityId());
            event.setEntityUserId(target.getUserId());
        }else if(comment.getEntityType() == ENTITY_TYPE_COMMENT){
            //评论 评论时
            Comment target = commentService.findCommentById(comment.getEntityId());
            event.setEntityUserId(target.getUserId());
        }
        //触发评论事件，系统通知 生产者发送消息
        eventProducer.fireEvent(event);
        //重定向到当前帖子的页面
        return "redirect:/discuss/detail/"+id;
    }
}
